package com.example.b_output;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class Demo1FileOutputStream {
    public static void main(String[] args) throws IOException {
//        method1();
//        method2();
        method3();
    }

    private static void method3() {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream("a.txt", true);
            fos.write("测试内容是否会清空\r\n".getBytes(StandardCharsets.UTF_8));
            fos.write("test1".getBytes(StandardCharsets.UTF_8));
            fos.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static void method1() throws IOException {
//        指定文件若不存在，输出流会自动进行创建，每执行一次都会新创建文件以覆盖前面创建的文件
        FileOutputStream fos = new FileOutputStream("ab.txt");
        fos.write(97);
        fos.close();
    }

    private static void method2() throws IOException {
        //    一次写一个字节数组
        FileOutputStream fos = new FileOutputStream("ab.txt");
        byte[] bytes = {97, 98, 99, 100};
        fos.write(bytes);
        fos.close();

//        一次写一个字节数组的一部分
        FileOutputStream fos1 = new FileOutputStream("1.txt");
        byte[] bytes1 = {97, 98, 99, 100, 101, 102, 103, 104};
        fos1.write(bytes1, 2, 3);
        fos1.close();
    }
}
